package com.dimpt.cloud.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dimpt.cloud.common.config.ResponseInfo;
import com.dimpt.cloud.common.utils.ResultUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

public class ResponseBodyWrapHandler implements HandlerMethodReturnValueHandler {

    private final HandlerMethodReturnValueHandler delegate;

    public ResponseBodyWrapHandler(HandlerMethodReturnValueHandler delegate) {
        this.delegate = delegate;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        Class clazz = returnType.getContainingClass();
        Package pack = clazz.getPackage();
        return pack.getName().startsWith("com.dimpt.cloud.api");
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        mavContainer.setRequestHandled(true);
        ResultUtils resultUtils = new ResultUtils(ResponseInfo.SUCCESS.getErrorCode(),ResponseInfo.SUCCESS.getErrorMsg(),returnValue);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);

        if (response != null) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len = JSON.writeJSONString(bos, resultUtils, SerializerFeature.WriteMapNullValue);
            response.setContentLength(len);
            response.addHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
            OutputStream os = response.getOutputStream();
            bos.writeTo(os);
            os.flush();
            os.close();
        }
    }
}
